package cn.doitedu.javase.blocking_queue;

import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;

public class ThreadPool {

    ArrayList<Thread> threads = new ArrayList<>();
    ArrayBlockingQueue<Runnable> userRunnableQueue = new ArrayBlockingQueue<>(5);

    /**
     * 线程池构造函数
     * @param size
     */
    public ThreadPool(int size){

        for(int i=0;i<size;i++) {
            // 初始化size个线程
            Thread thread = new Thread(new Worker(userRunnableQueue));
            thread.start();

            threads.add(thread);
        }

    }


    /**
     * 用户提交任务的入口
     * @param runnable
     */
    public void submit(Runnable runnable) throws InterruptedException {
        // 用一个线程，把传入的runnable跑起来
        userRunnableQueue.put(runnable);

        System.out.println("成功接收了一个用户的任务");

    }
}


class  Worker implements Runnable{

    ArrayBlockingQueue<Runnable> userRunnableQueue;

    public Worker(ArrayBlockingQueue<Runnable> userRunnableQueue){
        this.userRunnableQueue = userRunnableQueue;
    }

    @Override
    public void run() {
        try {
            while(true) {
                // 从 用户runnable队列中获取 用户 runnable
                Runnable userTask = userRunnableQueue.take();

                // 获取到之后，调用  用户 runnable.run()方法
                userTask.run();
            }
        }catch (Exception ignore){

        }

    }
}
